package cshi.common;

import scala.util.parsing.combinator.testing.Str;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.security.PrivilegedAction;
import java.util.concurrent.Callable;

/**
 * Created by shichen on 2017/10/31.
 */
public class LambdaTest {
    public static void main(String[] args) throws Exception {
        String oneline = processFile2((BufferedReader br) -> br.readLine());
        String twoline = processFile2((BufferedReader br) -> br.readLine() + br.readLine());
        System.out.print(oneline + ", " + twoline);

        //同样的lambda，不同的函数式接口
        Callable<Integer> c = () -> 42;
        PrivilegedAction<Integer> p = () -> 42;
    }

    //定义函数式接口
    @FunctionalInterface
    interface BufferedReaderProcessor {
        String process(BufferedReader b) throws IOException;
    }

    public static String processFile2(BufferedReaderProcessor bp) throws IOException {
        try (BufferedReader br =
            new BufferedReader(new FileReader(("pom.xml")))) {
            return bp.process(br);
        }
    }

    //这样写只能读取一行，要是想读二行呢？就需要对方法行为进行参数化
    //传递行为正是lambda的专长
    public static String processFile() throws IOException {
        try (BufferedReader br = new BufferedReader(new FileReader("pom.xml"))) { //这样写不需要显式关闭资源
            return br.readLine();
        }
    }
}
